package com.huawei.gatway.filters;

import com.huawei.common.utils.JwtUtil;
import com.huawei.common.utils.ThreadLocalUtil;
import com.huawei.gatway.properties.AuthProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.List;
import java.util.Map;


@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private AuthProperties authProperties;
    private AntPathMatcher antPathMatcher = new AntPathMatcher();


    //过滤器在网关实现登陆校验
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        System.out.println(request.getURI());
        //排除不需要校验的路径
        if(isExclude(request.getPath().toString())){
            return chain.filter(exchange);
        }

        String token = null;
        List<String> headers = request.getHeaders().get("Authorization");
        if(headers != null && !headers.isEmpty()){
            token = headers.get(0);
        }
        Map<String,Object> claims = null;
        try {
            ValueOperations<String, String> ops = redisTemplate.opsForValue();
            String redisToken = ops.get(token);
            if(redisToken == null){
                throw new RuntimeException();
            }

            claims = JwtUtil.parseToken(token);


        } catch (Exception e) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        String userId = claims.get("id").toString();
        String userName = claims.get("username").toString();
        ServerWebExchange swe = exchange.mutate()
                .request(builder -> builder.header("id",userId)).build();
        ServerWebExchange swe2 = swe.mutate()
                .request(builder -> builder.header("username", userName)).build();
        return chain.filter(swe2);
    }


    private boolean isExclude(String string) {
        for(String path : authProperties.getExcludePaths()){
            if (antPathMatcher.match(path,string)) {
                return true;
            }
        }
        return false;
    }


    @Override
    public int getOrder() {
        return 0;//越小优先级越高
    }
}












